import router from './router'
import store from './store'
import nprogress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// 引入动态路由
import { asyncRoutes } from '@/router/index'
const WhiteList = ['/login', '/404']
// 判断有没有token
router.beforeEach(async(to, from, next) => {
  // 先要开启进度条
  nprogress.start()
  // 进行判断,有无token
  if (store.getters.token) {
  // 再进行判断
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfoL')
        // console.log(roles)
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })// 筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        // 要把404页面放在最后 所以添加到筛选路由后面
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        // router添加动态路由之后 需要转发一下
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      } else {
        next()// 放过
      }
    }
  } else {
    // 如果没有token
    if (WhiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})
router.afterEach((to, from) => {
  // ...
  // 关闭进度条
  nprogress.done()
})
